/**
 * Created by no1 on 2015/8/28.
 */
'use strict';
var mysql = require('../mysql.js');
var C = require('../../config/index');
var F = require('../../common/function');
var o2o_F = require('../../common/o2ofunction');
var MPosts = require('../../model/posts.js');
var MTags = require('../../model/tags.js');
var MUser = require('../../model/users.js');
var Mman = require('../../common/man.js');
var imgRule = require('../../common/imgRule.js');
var _ = require('underscore');
var _s = require('underscore.string');
var md5 = require('md5');
var request = require('koa-request');
var async_request = require('request');
var logstash = require('./../logFlow/logstash.js');
_.v = require('validator');


/*
 *@todo API11 发布一个主题帖
 * */
exports.thread = function*(Env) {
  let fields = Env.I;
  let loginStatus = fields.loginStatus;
  var returnData = {};

  //var loginStatus = yield F.isLogin(Env);
  if (!loginStatus.status) {
    return F.returnMsg(401, '注册用户才能发帖', 3);
  }
  //if(loginStatus.groupid==4){ // gid=4 为禁止发言组
  //  return F.returnMsg(400, '用户已被限制发帖', 1);
  //}
  var ip = Env.ip;
  var manager = fields.manager;
  var version = fields.apiVerNum;
  var imgback = fields.imgback || 0;
  var thread_status=0;
  var vest_status = 0;
  if (parseInt(imgback) > 1) {
    return F.returnMsg(400, '必须上传jpg图', 1);
  }
  var isManager = false;
  if (manager && manager == 1 && F.isManager(loginStatus.groupid)) {
    isManager = true;
  }
  var imgext = '';//帖子图片扩展
  switch (imgback) {
    case '1':
      imgext = 'jpg';
      break;
    case '2':
      imgext = 'gif';
      break;
    case '3':
      imgext = 'png';
      break;
    default :
      //imgext = '';
      if (version < 3) {
        return F.returnMsg(400, '请选择上传一张图片', 1);
      }
      break;
  }
  var post =  _.str.trim(fields.post) || '';//帖子内容
  var video = fields.video || '';
  var minLen = 0;//发帖内容最短长度
  if (imgback == 0) {//无图
    minLen = 5;
  }
  if (!isManager) {
    if (imgback == 0) {//无图时必须写帖子内容
      if (!_.v.isLength(post, minLen, 250)) {
        return F.returnMsg(400, '内容必须在' + minLen + '至250字内', 1);
      }
    } else if (post.length > 250) {
      return F.returnMsg(400, '内容必须在250字内', 1);
    }
    video = '';
  } else {
    if (imgback == 0) {
      if (!_.v.isLength(post, minLen, 1000)) {
        return F.returnMsg(400, '内容必须在' + minLen + '至1000字内', 1);
      }
    } else if (post.length > 1000) {
      return F.returnMsg(400, '内容必须在1000字内', 1);
    }
    if (!_.v.isLength(video, 0)) {
      if (!_.v.isLength(video, 13, 30)) {
        return F.returnMsg(400, '视频关键字必须在13到30字内', 1);
      }
    }
  }
  var uid = loginStatus.uid;
  var nickName = loginStatus.nickname;
  if (post.length > 30 && !F.isManager(loginStatus.groupid)) {
    var postData = yield mysql.query('SELECT pid FROM mh_post_content WHERE uid=? AND post = ?', [uid, post]);
    if (postData.length > 1) {
      for (var i in postData) {
        yield this.delPost(Env, {act: 1, pid: parseInt(postData[i].pid), tokenkey: fields.tokenkey, status: 0});
      }
      return F.returnMsg(400, '禁止发广告帖。', 1);
    }
  }

  var imgDesc = fields.imgdesc || '';//帖子图片描述
  var tags = fields.tags || '';
  var flag = false;//是否强制加入随便聊聊标签
  if (version == 1) {//版本1
    var tagT = [{}];
    if (tags.length > 0) {
      var array = _.filter(tags.split(','), function (num) {
        return num > 0;
      });
      var y = 10;
      for (var i in array) {
        tagT[i] = {tagsType: 1, tagsid: array[i], tagstitle: '', x: 6, y: y};
        y += 13;
      }
    }
    tags = tagT;
    if (tags.length > 6) {
      return F.returnMsg(400, '最多只能添加6个标签', 1);
    }
    var isTagValid = yield F.isTagValid(tags);
    if (isTagValid.flag == false) {
      return F.returnMsg(400, isTagValid.msg, 1);
    }
  } else if (version == 2) {//版本2时传过来的为json格式
    /*2015.08.21【取消发帖强制标签限制】
     if (tags == '') {
     return F.returnMsg(400, '必须有一个标签且最多只能6个标签', 1);
     }*/
    tags = F.isJson(tags);
    if (!Array.isArray(tags) || tags.length > 6) {
      return F.returnMsg(400, '最多只能添加6个标签', 1);
    }
    var len = tags.length;
    var brondTagid = yield F.getBrondTagid();//话题下的标签id
    var lardTagid = C.lard_tagid;//随便聊聊标签id
    var tempTagidArr = [];
    for (var i = len - 1; i >= 0; i--) {
      if (tags[i].tagstitle == '' && tags[i].tagsid == 0) {
        tags.splice(i, 1);
      } else if (tags[i].tagsid > 0) {
        tempTagidArr.push(tags[i].tagsid);
      }
    }
    /*  2015.08.21 发帖时不强制加标签
     if (tags.length == 0) {
     return F.returnMsg(400, '最多只能6个标签', 1);
     }
     flag = _.v.isIn(lardTagid, tempTagidArr);
     if (_.isEmpty(_.intersection(tempTagidArr, brondTagid)) && !flag) {
     tags.push({"tagsType": 99, "tagsid": lardTagid, "tagstitle": "", "x": 0, "y": 0});
     }*/
  } else if (version >= 3) {
    var type = fields.type || 0;//0 普通帖 1 美容日志帖
    type = parseInt(type);
    if (!_.v.isIn(type, [0, 1,2])) {
      return F.returnMsg(400, 'type参数有误,请检查', 1);
    }
    var fid = fields.fid || 0;//帖子父id
    fid = parseInt(fid);
    var accessLevel = fields.accesslevel || 0;//公开级别 0 完全公开
    accessLevel = parseInt(accessLevel);
    if (!_.v.isIn(accessLevel, [0, 1])) {
      return F.returnMsg(400, '参数有误,请检查', 1);
    }
    var imgcount = fields.imgcount || 0;//图片数量
    imgcount = parseInt(imgcount);
    if (imgcount > 9) {
      return F.returnMsg(400, '最多上传9张图', 1);
    }
    if (type > 0) {//美容日志帖,有关联订单或者商品
      if (fid == 0) {//美容日记帖主贴
        var objectForDaily={};
        let title = _.str.trim(fields.title).replace(' ','') || '';//日记标题
        if (title == '') {
          return F.returnMsg(400, '日记标题不能为空', 1);
        } else if (!_.v.isLength(title, 1, 15)) {
          return F.returnMsg(400, '日记标题最只能是15个字符，请修改', 1);
        }


        //手术时间
        let firstDate=fields.firstDate||'';
        if(firstDate==''){
          return F.returnMsg(400, '请输入时间信息', 1);
        }
        if(!_.v.isDate(firstDate)){
          return F.returnMsg(400, '手术日期输入格式有错，请修改', 1);
        }
        firstDate = parseInt(new Date(firstDate + ' 0:0:0 CST+800').getTime() / 1000);


        //手术价格
        let price=fields.price||0;
        if(!_.v.isFloat(price)){
          return F.returnMsg(400, '价钱输入有误，请修改', 1);
        }

        //医生
        let doctor=fields.doctor||'';

        if(type==1){//关联商品
          let wareid = fields.wareid || 0;//获取第二个参数,产品id(当为管理员后台发日记帖时用)
          let orderid = fields.orderid || 0;//订单Id,当真实用户写美容日记帖时用
          //检查参数有效性
          if (isManager) {
            if (wareid == 0 || !_.v.isInt(wareid)) {
              return F.returnMsg(401, '商品参数错误，请检查再试！', 3);
            }
          } else if (orderid == 0 || !_.v.isInt(orderid)) {
            return F.returnMsg(401, '订单参数错误，请检查再试！', 3);
          }
          //check whether user did really buy that product and consume it already
          objectForDaily = yield F.orderData(loginStatus.uid, parseInt(orderid), parseInt(wareid), isManager);
          if (!objectForDaily.success) {
            if (isManager) {
              return F.returnMsg(400, '传入的产品id不存在，请检查.', 3);
            } else {
              return F.returnMsg(400, '您还没有消费该订单，暂时无法对其发表美容日记！', 3);
            }
          }
          objectForDaily = objectForDaily.orderData;
        } else if (type == 2) {//无关联订单或者商品
          let shopid=fields.shopid||0;
          if(shopid==0){
            return F.returnMsg(400, '请输入机构信息', 1);
          }
          let operationTags=fields.operationTags||'';
          if(operationTags==''){
            return F.returnMsg(400, '至少输入一个项目标签', 1);
          }
          operationTags=operationTags.split(',');
          if(operationTags.length>10){
            return F.returnMsg(400, '至多输入十个项目标签', 1);
          }
          let operation_detail_array=yield o2o_F.o2oGetOperationTagsByArray(operationTags);
          if(!_.v.isLength(operation_detail_array.length, 1, 10)){
            return F.returnMsg(400, '传入的项目标签在系统中未能找到', 1);
          }

           objectForDaily={
            shopid:shopid,tags:operation_detail_array,categoryId:operation_detail_array[0].code
          };
          //get shopName by shopid if passed in
          if(shopid>0){
            let ret = yield o2o_F.o2oGetShopInfoByShopId(shopid);
            if (!(parseInt(ret['result']['error']) == 1 || ret.status == 400)) {
              objectForDaily.shopName=ret['result'].name;
            }
          }
        }
        objectForDaily.title = _.str.trim(title);
        objectForDaily.firstDate=firstDate;
        objectForDaily.doctor=doctor;
        objectForDaily.operationPrice=price;
      }
    }

    if (fid > 0) {//有传父id
      type=0;//美容日记帖的系列贴将type置0
      let strSQL = 'SELECT tid,cid,uid FROM mh_thread WHERE `status`=1 AND type>0 AND tid=? ';
      let valArr = [fid];
      if (!isManager) {
        strSQL += ' AND uid=? ';
        valArr.push(loginStatus.uid);
      }
      var parentThread = yield mysql.query(strSQL, valArr);
      if (parentThread.length == 0) {
        return F.returnMsg(400, 'fid传入有误，未找到传入的fid', 1);
      }else{
        if (isManager){
          uid = parentThread[0].uid;
          loginStatus.vestuid = uid;
          vest_status = 1;
        }
      }
    }
    /*2015.08.21改为不需要加标签也可以发帖*/

    //if (tags == undefined || tags == '') {
    //    return F.returnMsg(400, '必须有一个标签且最多只能6个标签', 1);
    //}
    if (!(tags === undefined || tags == '')) {
      tags = F.isJson(tags.replace(/\\n/g,''));
    }
    //if (!tags) {
    //    return F.returnMsg(400, '必须有一个标签且最多只能6个标签', 1);
    //}
    var len = tags.length;//传过来的所有标签
    var tagLen = 0;//作为标签的长度
    var itemCount = 0;//作为项目的长度
    var brondTagid = yield F.getBrondTagid();//话题下的标签id
    var lardTagid = C.lard_tagid;//随便聊聊标签id
    var tempTagidArr = [];
    for (var i = len - 1; i >= 0; i--) {
      if (!_.v.isInt(tags[i].tagsid) || !_.isString(tags[i].tagstitle)) {//标签id必须是整形，可为0、内容必须为字符串
        continue;
      }
      tags[i].x = parseInt(tags[i].x);
      tags[i].y = parseInt(tags[i].y);
      if (tags[i].tagsType != 6 && imgcount > 0) {//作为项目的标签
        if ((!_.v.isInt(tags[i].x) || !_.v.isInt(tags[i].y)) || !_.v.isInt(
            tags[i].imgindex)) {
          continue;
        }
      }
      if (tags[i].tagsid > 0) {
        tempTagidArr.push(tags[i].tagsid);
      }
      var imgIndex = tags[i].imgindex || 0;//标签所在图的索引
      //if(imgIndex==undefined&&tags[i].tagsType!=6){
      //  return F.returnMsg(400, '没有指定某个标签在哪个图', 1);
      //}
      if (tags[i].tagstitle == '' && tags[i].tagsid == 0) {
        tags.splice(i, 1);
      } else {
        if (tags[i].tagsid == 0 && tags[i].tagstitle.length > 30) {
          return F.returnMsg(400, '标签长度不能大于30个字符', 1);
        }
        if (tags[i].tagsType == 6 && tags[i].tagsid != 0) {//作为项目的标签
          itemCount += 1;
        }
        /*2015.08.21可以发无标签帖子，不强制加标签
         else {
         if (parseInt(imgIndex) == 0) {//目前第一张图才强制加标签
         tagLen += 1;
         }*/
      }
    }
    //}
    //if(type==1&&itemCount==0){//美容日志帖
    //  return F.returnMsg(400, '项目必须有一个', 1);
    //}
    if (tagLen > 6 && imgcount > 0) {
      return F.returnMsg(400, '最多只能6个标签', 1);
    }
    /*2015.08.21 不强制给帖子加标签
     flag = _.v.isIn(lardTagid, tempTagidArr);
     if (_.isEmpty(_.intersection(tempTagidArr, brondTagid)) && !flag) {
     tags.push({"tagsType": 99, "tagsid": lardTagid, "tagstitle": "", "x": 0, "y": 0});
     }*/
    //验证图片描述json串开始
    if (imgDesc != '') {
      var imgDescLen = imgDesc.length;
      if (imgDescLen > 2045) {//数据表字段类型varchar，长度2048
        return F.returnMsg(400, '图片描述内容太长', 1);
      }
      var tmpImgDesc = F.isJson(imgDesc);
      if (tmpImgDesc) {
        if (tmpImgDesc.desc !== undefined) {
          var tmpArr = tmpImgDesc.desc;
          if (!Array.isArray(tmpArr)) {
            return F.returnMsg(400, '参数有误,请检查', 1);
          }
          for (var i in tmpArr) {
            if (!_.isString(tmpArr[i])) {
              return F.returnMsg(400, '参数有误,请检查', 1);
            }
          }
        } else {
          return F.returnMsg(400, '参数有误,请检查', 1);
        }
      } else {
        return F.returnMsg(400, '参数有误,请检查', 1);
      }
    }
    //验证图片描述json串结束
    var validimg = '';//有效图片
    for (var i = 0; i < imgcount; i++) {
      validimg += validimg == '' ? i + '-1' : ',' + i + '-1';
    }
  }
  var cid_data = {ctype: 0};
  // 判断类别
  if (fid > 0) {//美容日记帖沿用父贴圈子
    var cid = parentThread[0]['cid'];
  } else {
    var cid = fields.cid || -1;

    if (_.v.isIn(type, [1, 2])) {//如果是美容日记帖，去Mongo数据库查询类别对应的圈子
      cid =yield o2o_F.o2oGetThreadCategory(objectForDaily.categoryId);
    }

    if (isManager) {//管理员发帖
      uid = loginStatus.vestuid;
      nickName = loginStatus.vestnickname;
      vest_status = 1;
    } else {//如果不是管理员发帖将检查发帖内容
      if (type == 0) {
        let data = {cid: cid, post: post, isSPAM: fields._isSPAM};//isSPAM: 搜索是否含有敏感关键字
        cid_data = {//初始化cid_data
          cid: cid,
          cid_display: cid,
          SPAM: fields._isSPAM,
          ctype: 0 //分类方式，0为用户分类，1人工分类，2机器分类
        };
        cid_data = yield F.checkCid(data);

        cid = cid_data.cid;
        if (cid_data.SPAM == 1) {
          thread_status = 2;//vest_status用作更新thread.status用，如果是广告贴，则将status改成2
        }
        returnData.cid_display = cid_data.cid_display;
        returnData.cid=cid;
        returnData.ctype=cid_data.ctype;
      }
    }
  }
  //验证帖子类别是否存在
  var isCid = yield mysql.query('select cid from mh_thread_category where ctype=1 and cid=?', [cid]);
  if (!(isCid && isCid.length > 0)) {
    return F.returnMsg(400, '种类不存在', 1);
  }

  // 得到新的pid
  var newPost = yield mysql.query('INSERT INTO mh_post_table VALUES()');
  var pid = newPost.insertId;
  if (pid.insertId < 1) {
    return F.returnMsg(400, '发布失败', 1);
  }
  //2015.12.16 add simulation tag
  let simulation=fields.simulation || 0;//是否模拟整容贴
  // 插入主表mh_thread
  if (version < 3) {
    var isThreadSuccess = yield mysql.query('INSERT INTO mh_thread(pid,uid,timeline,closed,status,lastpost,vest) VALUES(?,?,UNIX_TIMESTAMP(),0,0,UNIX_TIMESTAMP(),?)', [pid, uid, vest_status]);
  } else {
    var isThreadSuccess = yield mysql.query('INSERT INTO mh_thread(pid,uid,cid,timeline,closed,status,lastpost,fid,type,accesslevel,imgcount,validimg,vest,video,ctype,simulation_thread)' +
      ' VALUES(?,?,?,UNIX_TIMESTAMP(),0,?,UNIX_TIMESTAMP(),?,?,?,?,?,?,?,?,?)', [pid, uid, cid,thread_status, fid, type, accessLevel, imgcount, validimg, vest_status, video,cid_data.ctype,simulation]);
  }
  var tid = isThreadSuccess.insertId;
  if (tid < 1) {
    return F.returnMsg(400, '发布失败', 1);
  } else {//发帖成功后的操作
    //如果是美容日记帖的更新日记，更新lastUpdate字段
    if(fid>0){
      mysql.query('update mh_thread_extend set lastUpdate=UNIX_TIMESTAMP() where tid=?',[fid]);
    }

    //更新类别热度
    mysql.query('UPDATE mh_thread_category SET threads=threads+1 WHERE cid=?', [cid]);

    //记录用户的前三个cid
    let uid = loginStatus.uid;
    if (cid_data.SPAM == 1) {//如果是被系统界定为广告类别，将最近使用类别换成默认的类别
      cid=cid_data.cid_display;
    }
    let tempres = yield mysql.query('SELECT lastestcategories FROM mh_user_info WHERE uid=?', [uid]);
    let old_user_cats = tempres[0].lastestcategories;
    if (old_user_cats === '') {//用户lastestcategories没有记录
      mysql.query('update mh_user_info SET  lastestcategories=? where uid=?', [cid, uid])
    } else {//用户有lastestcategories记录
      let arr = old_user_cats.split(",");
      let i = 0;
      let inarr = false;
      for (let one in arr) {
        if (parseInt(arr[one]) == cid) {//cid在之前记录中
          arr.splice(i, 1);
          arr.unshift(cid);
          inarr = true;
        }
        i++;
      }
      if (!inarr) {//cid不在之前记录中
        if (arr.length >= 3) {
          //arr.slice(2, (arr.length - 2));
          arr.splice(2, (arr.length - 2));
          arr.unshift(cid);
        } else {
          arr.unshift(cid);
        }
      }
      let new_user_cats = arr.toString();
      mysql.query('update mh_user_info SET  lastestcategories=? where uid=?', [new_user_cats, uid])
    }

  }
  // 插入mh_post
  var isPostSuccess = yield mysql.query('INSERT INTO mh_post(pid,tid,imgext,uid,timeline,status,first,ip,vest) VALUES(?,?,?,?,UNIX_TIMESTAMP(),0,1,?,?)', [pid, tid, imgext, uid, ip, vest_status]);
  if (isPostSuccess.affectedRows < 1) {
    mysql.query('DELETE FROM mh_thread WHERE tid=?', [tid]);//删除主题帖
    return F.returnMsg(400, '发布失败', 1);
  }
  // 插入mh_post_content保存帖子内容
  var isPostContentSuccess = yield mysql.query('INSERT INTO mh_post_content(tid,pid,post,imgdesc,uid,first) VALUES(?,?,?,?,?,1)', [tid, pid, post, imgDesc, uid]);
  if (isPostContentSuccess.affectedRows < 1) {
    mysql.query('DELETE FROM mh_thread WHERE tid=?', [tid]);//删除主题帖
    mysql.query('DELETE FROM mh_post WHERE pid=?', [pid]);//删除回帖
    return F.returnMsg(400, '发布失败', 1);
  }

  // logstash 流程
  var json = {
    uid: uid,
    vest: vest_status,
    tid: tid,
    action: 'post',
    articleContent: post,
    cid: Number(cid),
    imgcount: imgcount
  };
  logstash.article(json);

  //美容日志帖子补充内容开始(关联商品或者订单)
  if (version >= 3 && type == 1 && fid == 0) {//版本3且是美容日志帖主贴
     yield mysql.query('INSERT INTO mh_thread_extend(tid,orderid,title,wareid,wareName,price,consumeDate,categoryId,categoryName,vendorid,vendorName,firstDate,operationPrice,doctor,lastUpdate) ' +
      'VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,UNIX_TIMESTAMP())', [tid, objectForDaily.orderid, objectForDaily.title, objectForDaily.wareid, objectForDaily.wareName,
       objectForDaily.price, objectForDaily.consume_date, objectForDaily.categoryId, objectForDaily.categoryName,
       objectForDaily.vendorid, objectForDaily.vendorName,objectForDaily.firstDate,objectForDaily.operationPrice,objectForDaily.doctor]);
     mysql.query('update mh_order set daily_thread_id=? where orderid=?',[tid,objectForDaily.orderid])
  }else if (version >= 3 && type == 2 && fid == 0){//无关联商品或订单
    yield mysql.query('INSERT INTO mh_thread_extend(tid,title,operationPrice,firstDate,doctor,shopid,shopName,lastUpdate) ' +
        'VALUES(?,?,?,?,?,?,?,UNIX_TIMESTAMP())', [tid, objectForDaily.title, objectForDaily.operationPrice, objectForDaily.firstDate, objectForDaily.doctor,
      objectForDaily.shopid, objectForDaily.shopName]);
    for(let tag of objectForDaily.tags){
     yield mysql.query('INSERT INTO mh_thread_tags(tid,tagsid,tagstype,tagstitle,imgindex) VALUES(?,?,?,?,?)', [tid,tag.code,6,tag.name,-1]);
    }
  }
  //美容日志帖子补充内容结束
  // 记录标签
  for (var i in tags) {
    var tagData = tags[i];
    var tagsType = parseInt(tagData.tagsType);
    if (tagsType != 1 && tagsType != 2 && tagsType != 3 && tagsType != 4 && tagsType != 5 && tagsType != 6 && tagsType != 99) {//目前标签类型只有1，2，3，4，5,6
      continue;
    }
    if (tagsType == 99 && flag) {
      continue;
    }
    var tagsid = tagData.tagsid ? parseInt(tagData.tagsid) : 0;
    var tagstitle = tagData.tagstitle || '';
    var x = tagData.x ? parseInt(tagData.x) : 0;
    var y = tagData.y ? parseInt(tagData.y) : 0;


    var placeLeft = tagData.x > 50 ? 1 : 0;
    if (_.v.isIn(tagData.placeLeft, [0, 1])) {
      placeLeft = tagData.placeLeft;
    }

    var imgIndex = tagData.imgindex !== undefined ? parseInt(tagData.imgindex) : 0;//版本3之前没多图,故不用传标签的图索引
    var poiid = '';
    switch (tagsType) {
      case 1://传统标签
      case 4://lbs标签
      case 5://传统标签中的水印标签
      case 6://美容标签
      case 99://随便聊聊标签
        if (tagsid == 0) {//没传标签id过来
          if (tagstitle == '') {
            continue;
          }
          var tmpTagData = yield mysql.query('SELECT tagid FROM mh_tags WHERE tagtitle=?', [tagstitle]);
          if (tmpTagData.length > 0) {//已经存在标签
            tagsid = tmpTagData[0].tagid;
          } else {
            var retTag = yield mysql.query('INSERT INTO mh_tags(tagtype,tagtitle,uid) VALUES(?,?,?)', [2, tagstitle, uid]);//2 为用户自定义标签
            tagsid = retTag.insertId;
          }
        } else {//有传标签id过来
          var addWhere = '';
          if (tagsType == 6) {//美容标签类型
            addWhere += ' AND tagtype=4'
          }
          var tTag = yield mysql.query('SELECT tagid,tagtitle FROM mh_tags WHERE tagid=?' + addWhere, [tagsid]);
          if (tTag.length > 0) {
            tagstitle = tTag[0].tagtitle;
          } else {
            continue;
          }
        }
        if (tagsType == 4 && tagData.poiid) {
          //写poi详细开始
          poiid = tagData.poiid;
          var poiDetail = yield mysql.query('SELECT version,poiid,pcode,pname,citycode,cityname,adcode,adname,address,`name`,longitude,latitude FROM mh_poi_detail WHERE version=? AND poiid=?', [C.amap.api_ver, poiid]);
          if (poiDetail.length == 0) {
            F.AMAPSearchPoi([poiid],
              function (jsonData, pois) {
                var poisArr = jsonData.pois;
                mysql.query('insert into mh_poi_detail(version,poiid,pcode,pname,citycode,cityname,adcode,adname,address,`name`,longitude,latitude,poidetail,lasttid,tagid) values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)', [C.amap.api_ver, pois.id, pois.pcode, pois.pname, pois.citycode, pois.cityname, pois.adcode, pois.adname, pois.address, pois.name, pois.longitude, pois.latitude, JSON.stringify(poisArr), tid, tagsid]);
                F.savePoi2Mongo({
                  poiid: pois.id,
                  name: pois.name,
                  tagid: tagsid,
                  longitude: pois.longitude,
                  latitude: pois.latitude
                });
              }
            );
          } else {
            mysql.query('UPDATE mh_poi_detail SET lasttid=? WHERE version=? AND poiid=?', [tid, C.amap.api_ver, poiid]);
          }
          //写poi详细结束
        }
        break;
      case 2://用户标签
        break;
      case 3://帖子标签
        break;
    }
    mysql.query('INSERT INTO mh_thread_tags(tid,tagsid,tagstype,tagstitle,x,y,imgindex,poiid,placeLeft) VALUES(?,?,?,?,?,?,?,?,?)', [tid, tagsid, tagsType, tagstitle, x, y, imgIndex, poiid, placeLeft]);
    if (tagsType == 1 || tagsType == 4 || tagsType == 5 || tagsType == 6) {//传统标签，水印标签、美容标签时写入最后一个发帖
      mysql.query('UPDATE mh_tags SET lasttid=? WHERE tagid=?', [tid, tagsid]);
    }
  }


  let imgArray = [];
  if (!imgback || imgback == 0) {

  } else {
    // 又拍云参数
    var crop = Env.I.crop;
    if (version > 2) {//大于版本2后，支持上传
      var signArr = [];
      for (var i = 0; i < imgcount; i++) {
        var upyun = {
          type: 2,
          pid: pid,
          imgBack: imgback,
          imgindex: i//图片索引
        };
        if (crop) {
          upyun['crop'] = crop;
        }
        //signArr[i] = yield F.getUpyunSign(upyun);
        let imgStr = imgRule.id2imgStr('P', pid, 'jpg');
        imgArray.push(imgStr);
        signArr[i] = yield F.getUpyunSignB(imgRule.str2imgURI(imgStr)[0]);
        signArr[i].tid = tid;
      }
      mysql.query('UPDATE mh_thread SET imagestring=?  WHERE tid=?', [imgArray.join(','), tid]);
      returnData.upYunSign = signArr;
    } else {
      var upyun = {
        type: 2,
        pid: pid,
        imgBack: imgback
      };
      if (crop) {
        upyun['crop'] = crop;
      }
      let imgStr = imgRule.id2imgStr('P', pid, 'jpg');
      mysql.query('UPDATE mh_thread SET imagestring=?  WHERE tid=?', [imgArray.join(','), tid]);
      returnData = yield F.getUpyunSignB(imgRule.str2imgURI(imgStr));
      //returnData = yield F.getUpyunSign(upyun);
    }
  }



  //插入图片信息开始
  var imgInfo = fields.imgInfo === undefined ? '' : fields.imgInfo;//图片信息，包含图片的索引，图片是否自拍，是否使用过滤镜,是否整形图片
  imgInfo = F.isJson(imgInfo.replace(/\\n/g,''));
  if (imgInfo) {
    for (let i in imgInfo) {
      let rec = {};
      rec.wmark = parseInt(imgInfo[i].wmark|0);
      rec.selfie = parseInt(imgInfo[i].selfie|0);
      rec.simulation = parseInt(imgInfo[i].simulation | 0);

      if (Array.isArray(imgInfo[i].filter)){
        rec.filter = parseInt(imgInfo[i].filter[0]|0);
        rec.filter2 = parseInt(imgInfo[i].filter[1]|0);
      }else{ // 兼容之前接口
        rec.filter = 0;
        rec.filter2 = parseInt(imgInfo[i].filter|0);
      }

      rec.imgstr = imgArray[i]|'';
      console.log('Img:'+rec.imgstr);
      //if (parseInt(imgInfo[i].imgindex) < imgcount && _.v.isIn(parseInt(imgInfo[i].selfie), [0, 1]) && _.v.isInt(imgInfo[i].filter)) {
        //if (imgInfo[i].selfie > 0 && imgInfo[i].filter > 0) {
      mysql.query('INSERT INTO mh_thread_imginfo(tid,imgindex,selfie,filter,filter2,wmark,imagestring,simulation) VALUES(?,?,?,?,?,?,?,?)',
        [tid,
          i,
          rec.selfie,
          rec.filter,
          rec.filter2,
          rec.wmark,
          rec.imgstr,
          rec.simulation
        ]
      );
        //}
      //}
    }
  }
  //插入图片信息结束
  if (F.isManager(loginStatus.groupid)) {
    mysql.query('INSERT INTO mh_vest_post(tid,pid,uid,vid,timeline) VALUES(?,?,?,?,UNIX_TIMESTAMP())', [tid, pid, loginStatus.uid, loginStatus.vestuid]);//管理员发帖
  }



  if (_.v.isLength(video, 13, 30)) {
    var videoimgSign = {
      type: 2,
      pid: pid,
      imgBack: imgback,
      imgindex: 'video'//图片索引或者是视频截图标记
    };
    let imgStr = imgRule.id2imgStr('P', tid, 'jpg', 'video');
    returnData.videoimgSign = yield F.getUpyunSignB(imgRule.str2imgURI(imgStr));
    //returnData.videoimgSign = yield F.getUpyunSign(videoimgSign);
  }

  //保存发帖提交
  var key = C.redisPre.thread_user;
  key = _s.sprintf(key, parseInt(tid));
  var expire = C.redisPre.thread_user_ttl;
  F.redisClient.SETEX(key, expire, uid);
  //保存发帖结束
  returnData.tid = tid;

  return F.returnMsg(200, '提交成功', 3, returnData);
};
